<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryForm" size="small" :inline="true" v-show="showSearch" label-width="68px">
      <el-form-item label="文件编号" prop="fileId">
        <el-input
          v-model="queryParams.fileId"
          placeholder="请输入文件编号"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item prop="folderId" style="width: 25%">
        <el-row :gutter="24">
          <el-col :span="6">
            <span style=" font-weight: bold;color: rgb(96, 98, 102)">文件夹</span>
          </el-col>
          <el-col :span="18">
            <treeselect v-model="queryParams.folderId"
                        :options="folderInfoOptions" :show-count="true" :normalizer="normalizer"
                        placeholder="请选择文件夹"

            />
          </el-col>
        </el-row>
      </el-form-item>
      <el-form-item label="文件名" prop="fileName">
        <el-input
          v-model="queryParams.fileName"
          placeholder="请输入文件名"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="文件类型" prop="fileType">
        <el-select v-model="queryParams.fileType" placeholder="请选择文件类型" clearable>
          <el-option
            v-for="dict in dict.type.n_file_type"
            :key="dict.value"
            :label="dict.label"
            :value="dict.value"
          />
        </el-select>
      </el-form-item>
      <el-form-item label="文件后缀" prop="fileSuffix">
        <el-input
          v-model="queryParams.fileSuffix"
          placeholder="请输入文件后缀"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="文件标签" prop="tagId">
        <el-select
          style="width: 100%"
          v-model="queryParams.tagId"
          filterable
          remote
          reserve-keyword
          placeholder="请输入标签名称"
          :remote-method="selectTagList"
          :loading="tagLoading"
        >
          <el-option
            v-for="item in tagList"
            :key="item.tagId"
            :label="item.tagName"
            :value="item.tagId"
          >
          </el-option>
        </el-select>
      </el-form-item>
      <el-form-item label="创建时间">
        <el-date-picker
          v-model="daterangeCreateTime"
          style="width: 240px"
          value-format="yyyy-MM-dd"
          type="daterange"
          range-separator="-"
          start-placeholder="开始日期"
          end-placeholder="结束日期"
        ></el-date-picker>
      </el-form-item>
      <el-form-item label="更新时间">
        <el-date-picker
          v-model="daterangeUpdateTime"
          style="width: 240px"
          value-format="yyyy-MM-dd"
          type="daterange"
          range-separator="-"
          start-placeholder="开始日期"
          end-placeholder="结束日期"
        ></el-date-picker>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
        <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button
          type="primary"
          plain
          icon="el-icon-plus"
          size="mini"
          @click="handleAdd"
          v-hasPermi="['manage:fileInfo:add']"
        >新增
        </el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="success"
          plain
          icon="el-icon-edit"
          size="mini"
          :disabled="single"
          @click="handleUpdate"
          v-hasPermi="['manage:fileInfo:edit']"
        >修改
        </el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="danger"
          plain
          icon="el-icon-delete"
          size="mini"
          :disabled="multiple"
          @click="handleDelete"
          v-hasPermi="['manage:fileInfo:remove']"
        >删除
        </el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="warning"
          plain
          icon="el-icon-download"
          size="mini"
          @click="handleExport"
          v-hasPermi="['manage:fileInfo:export']"
        >导出
        </el-button>
      </el-col>
      <right-toolbar :showSearch.sync="showSearch" @queryTable="getList" :columns="columns"></right-toolbar>
    </el-row>

    <el-table v-loading="loading" :data="fileInfoList" @selection-change="handleSelectionChange">
      <el-table-column type="selection" width="55" align="center"/>
      <el-table-column label="文件编号" align="center" v-if="columns[0].visible" prop="fileId"/>
      <el-table-column label="文件夹" :show-overflow-tooltip="true" align="center" v-if="columns[1].visible"
                       prop="folderName"/>
      <el-table-column label="文件名" :show-overflow-tooltip="true" align="center" v-if="columns[2].visible"
                       prop="fileName"/>
      <el-table-column label="文件类型" align="center" v-if="columns[3].visible" prop="fileType">
        <template slot-scope="scope">
          <dict-tag :options="dict.type.n_file_type" :value="scope.row.fileType"/>
        </template>
      </el-table-column>
      <el-table-column label="文件路径" align="center" v-if="columns[4].visible" prop="fileUrl" width="100">
        <template slot-scope="scope">
          <image-preview v-if="scope.row.fileType==='1'" :src="scope.row.fileUrl"/>
          <el-link v-else v-show="scope.row.fileUrl!=null"
                   :download="getFileName(scope.row.fileUrl)"
                   :href="baseUrl+scope.row.fileUrl"
                   :underline="false"
                   target="_blank"
          >
            <span style="cursor: pointer;"> 下载 </span>
          </el-link>
        </template>
      </el-table-column>
      <el-table-column label="文件后缀" :show-overflow-tooltip="true" align="center" v-if="columns[5].visible"
                       prop="fileSuffix"/>
      <!--      <el-table-column label="排序权重" :show-overflow-tooltip="true" align="center" v-if="columns[6].visible"-->
      <!--                       prop="sortNum"/>-->
      <el-table-column label="文件标签" :show-overflow-tooltip="true" align="center" v-if="columns[7].visible"
                       prop="tagName"/>
      <el-table-column label="创建人" :show-overflow-tooltip="true" align="center" v-if="columns[8].visible"
                       prop="userName"/>
      <el-table-column label="创建时间" align="center" v-if="columns[9].visible" prop="createTime" width="180">
        <template slot-scope="scope">
          <span>{{ parseTime(scope.row.createTime, '{y}-{m}-{d}') }}</span>
        </template>
      </el-table-column>
      <el-table-column label="更新时间" align="center" v-if="columns[10].visible" prop="updateTime" width="180">
        <template slot-scope="scope">
          <span>{{ parseTime(scope.row.updateTime, '{y}-{m}-{d}') }}</span>
        </template>
      </el-table-column>
      <el-table-column label="备注" :show-overflow-tooltip="true" align="center" v-if="columns[11].visible"
                       prop="remark"/>
      <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
        <template slot-scope="scope">
          <el-button
            size="mini"
            type="text"
            icon="el-icon-edit"
            @click="handleUpdate(scope.row)"
            v-hasPermi="['manage:fileInfo:edit']"
          >修改
          </el-button>
          <el-button
            size="mini"
            type="text"
            icon="el-icon-delete"
            @click="handleDelete(scope.row)"
            v-hasPermi="['manage:fileInfo:remove']"
          >删除
          </el-button>
        </template>
      </el-table-column>
    </el-table>

    <pagination
      v-show="total>0"
      :total="total"
      :page.sync="queryParams.pageNum"
      :limit.sync="queryParams.pageSize"
      @pagination="getList"
    />

    <!-- 添加或修改文件信息对话框 -->
    <el-dialog :title="title" :visible.sync="open" width="500px" append-to-body>
      <el-form ref="form" :model="form" :rules="rules" label-width="80px">
        <el-form-item label="文件夹" prop="folderId">
          <treeselect v-model="form.folderId" :options="folderInfoOptions" :normalizer="normalizer"
                      placeholder="请选择父级"/>
        </el-form-item>
        <el-form-item label="文件名" prop="fileName">
          <el-input v-model="form.fileName" placeholder="请输入文件名"/>
        </el-form-item>
        <el-form-item label="文件类型" prop="fileType">
          <el-select v-model="form.fileType" placeholder="请选择文件类型">
            <el-option
              v-for="dict in dict.type.n_file_type"
              :key="dict.value"
              :label="dict.label"
              :value="dict.value"
            ></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="文件路径" prop="fileUrl">
          <image-upload v-if="form.fileType==='1'" :file-size="100" :limit="1" v-model="form.fileUrl"/>
          <file-upload v-else :limit="1" :file-size="5000" v-model="form.fileUrl"
                       :file-type="fileType"/>
        </el-form-item>
        <!--        <el-form-item label="文件后缀" prop="fileSuffix">-->
        <!--          <el-input v-model="form.fileSuffix" placeholder="请输入文件后缀"/>-->
        <!--        </el-form-item>-->
        <el-form-item label="排序权重" prop="sortNum">
          <el-input-number :min="0" :max="10" v-model="form.sortNum" placeholder="请输入排序权重"/>
        </el-form-item>
        <el-form-item label="文件标签" prop="tagId">
          <el-select
            style="width: 100%"
            v-model="form.tagId"
            filterable
            remote
            reserve-keyword
            placeholder="请输入标签名称"
            :remote-method="selectTagList"
            :loading="tagLoading"
          >
            <el-option
              v-for="item in tagList"
              :key="item.tagId"
              :label="item.tagName"
              :value="item.tagId"
            >
            </el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="备注" prop="remark">
          <el-input v-model="form.remark" placeholder="请输入备注"/>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import {listFileInfo, getFileInfo, delFileInfo, addFileInfo, updateFileInfo} from "@/api/manage/fileInfo";
import Treeselect from "@riophae/vue-treeselect";
import "@riophae/vue-treeselect/dist/vue-treeselect.css";
import {listFolderInfo} from "@/api/manage/folderInfo";
import {listTagInfo} from "@/api/manage/tagInfo";

export default {
  name: "FileInfo",
  components: {Treeselect},
  dicts: ['n_file_type'],
  data() {
    return {
      fileType: ["doc", "docx", "xls", "xlsx", "ppt", "pptx", "html", "htm", "txt", "rar", "zip", "gz", "bz2", "mp4", "avi", "rmvb", "pdf"],
      //文件夹
      // 文件夹信息树选项
      folderInfoOptions: [],
      //标签信息
      tagList: [],
      tagLoading: false,
      tagQueryParams: {
        tagName: '',
        pageNum: 1,
        pageSize: 100
      },
      baseUrl: process.env.VUE_APP_BASE_API,
      //表格展示列
      columns: [
        {key: 0, label: '文件编号', visible: true},
        {key: 1, label: '文件夹编号', visible: true},
        {key: 2, label: '文件名', visible: true},
        {key: 3, label: '文件类型', visible: true},
        {key: 4, label: '文件路径', visible: true},
        {key: 5, label: '文件后缀', visible: true},
        {key: 6, label: '排序权重', visible: true},
        {key: 7, label: '文件标签', visible: true},
        {key: 8, label: '创建人', visible: true},
        {key: 9, label: '创建时间', visible: true},
        {key: 10, label: '更新时间', visible: false},
        {key: 11, label: '备注', visible: false},
      ],
      // 遮罩层
      loading: true,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 文件信息表格数据
      fileInfoList: [],
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      // 备注时间范围
      daterangeCreateTime: [],
      // 备注时间范围
      daterangeUpdateTime: [],
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        fileId: null,
        folderId: null,
        fileName: null,
        fileType: null,
        fileSuffix: null,
        tagId: null,
        createTime: null,
        updateTime: null,
      },
      // 表单参数
      form: {},
      // 表单校验
      rules: {
        folderId: [
          {required: true, message: "文件夹编号不能为空", trigger: "blur"}
        ],
        fileName: [
          {required: true, message: "文件名不能为空", trigger: "blur"}
        ],
        fileType: [
          {required: true, message: "文件类型不能为空", trigger: "change"}
        ],
        fileUrl: [
          {required: true, message: "文件路径不能为空", trigger: "blur"}
        ],
        fileSuffix: [
          {required: true, message: "文件后缀不能为空", trigger: "blur"}
        ],
        sortNum: [
          {required: true, message: "排序权重不能为空", trigger: "blur"}
        ],
        userId: [
          {required: true, message: "创建人不能为空", trigger: "blur"}
        ],
        createTime: [
          {required: true, message: "创建时间不能为空", trigger: "blur"}
        ],
      }
    };
  },
  created() {
    this.getList();
    this.getTreeselect()
    this.getTagList()
  },
  methods: {
    /** 转换文件夹信息数据结构 */
    normalizer(node) {
      if (node.children && !node.children.length) {
        delete node.children;
      }
      return {
        id: node.folderId,
        label: node.folderName,
        children: node.children
      };
    },
    /** 查询文件夹信息下拉树结构 */
    getTreeselect() {
      listFolderInfo().then(response => {
        this.folderInfoOptions = [];
        const data = {folderId: 0, folderName: '顶级节点', children: []};
        data.children = this.handleTree(response.data, "folderId", "parentId");
        this.folderInfoOptions.push(data);
      });
    },
    /**
     * 获取标签列表推荐
     * @param query
     */
    selectTagList(query) {
      if (query !== '') {
        this.tagLoading = true
        this.tagQueryParams.tagName = query
        setTimeout(() => {
          this.getTagList()
        }, 200)
      } else {
        this.tagList = []
      }
    },
    /**
     * 获取标签信息列表
     */
    getTagList() {
      //添加查询参数
      if (this.form.tagId != null) {
        this.tagQueryParams.tagId = this.form.tagId
      } else {
        this.tagQueryParams.tagId = null
      }
      if (this.tagQueryParams.tagName != null) {
        this.tagQueryParams.tagId = null
      }
      listTagInfo(this.tagQueryParams).then(res => {
        this.tagList = res.rows
        this.tagLoading = false
      })
    },
    /** 查询文件信息列表 */
    getList() {
      this.loading = true;
      this.queryParams.params = {};
      if (null != this.daterangeCreateTime && '' != this.daterangeCreateTime) {
        this.queryParams.params["beginCreateTime"] = this.daterangeCreateTime[0];
        this.queryParams.params["endCreateTime"] = this.daterangeCreateTime[1];
      }
      if (null != this.daterangeUpdateTime && '' != this.daterangeUpdateTime) {
        this.queryParams.params["beginUpdateTime"] = this.daterangeUpdateTime[0];
        this.queryParams.params["endUpdateTime"] = this.daterangeUpdateTime[1];
      }
      listFileInfo(this.queryParams).then(response => {
        this.fileInfoList = response.rows;
        this.total = response.total;
        this.loading = false;
      });
    },
    //获取文件名 此功能只可以下载只有一个文件的
    getFileName(filePath) {
      if (filePath == null) {
        return
      }
      // 提取文件名或根据需求生成文件名
      const fileName = filePath.substring(filePath.lastIndexOf('/') + 1)
      return fileName
    },
    // 取消按钮
    cancel() {
      this.open = false;
      this.reset();
    },
    // 表单重置
    reset() {
      this.form = {
        fileId: null,
        folderId: null,
        fileName: null,
        fileType: null,
        fileUrl: null,
        fileSuffix: null,
        sortNum: null,
        tagId: null,
        userId: null,
        createTime: null,
        updateTime: null,
        remark: null
      };
      this.resetForm("form");
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1;
      this.getList();
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.daterangeCreateTime = [];
      this.daterangeUpdateTime = [];
      this.resetForm("queryForm");
      this.getTagList()
      this.getTreeselect()
      this.handleQuery();
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map(item => item.fileId)
      this.single = selection.length !== 1
      this.multiple = !selection.length
    },
    /** 新增按钮操作 */
    handleAdd() {
      this.reset();
      this.open = true;
      this.title = "添加文件信息";
    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      this.reset();
      const fileId = row.fileId || this.ids
      getFileInfo(fileId).then(response => {
        this.form = response.data;
        this.getTagList()
        this.open = true;
        this.title = "修改文件信息";
      });
    },
    /** 提交按钮 */
    submitForm() {
      this.$refs["form"].validate(valid => {
        if (valid) {
          if (this.form.fileId != null) {
            updateFileInfo(this.form).then(response => {
              this.$modal.msgSuccess("修改成功");
              this.open = false;
              this.getList();
            });
          } else {
            addFileInfo(this.form).then(response => {
              this.$modal.msgSuccess("新增成功");
              this.open = false;
              this.getList();
            });
          }
        }
      });
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      const fileIds = row.fileId || this.ids;
      this.$modal.confirm('是否确认删除文件信息编号为"' + fileIds + '"的数据项？').then(function () {
        return delFileInfo(fileIds);
      }).then(() => {
        this.getList();
        this.$modal.msgSuccess("删除成功");
      }).catch(() => {
      });
    },
    /** 导出按钮操作 */
    handleExport() {
      this.download('manage/fileInfo/export', {
        ...this.queryParams
      }, `fileInfo_${new Date().getTime()}.xlsx`)
    }
  }
};
</script>
